import java.util.LinkedList;

public class LinkedCalculate {
    public static LinkedList<Integer> subtract(LinkedList<Integer> l1, LinkedList<Integer> l2) {
        LinkedList<Integer> result = new LinkedList<>();
        //借位
        int borrow = 0;
        while (!l1.isEmpty() || !l2.isEmpty()) {
            int x = !l1.isEmpty() ? l1.removeLast() : 0;
            int y = !l2.isEmpty() ? l2.removeLast() : 0;

            int diff = x - y - borrow;

            if (diff < 0) {
                diff += 10;
                borrow = 1;
            } else {
                borrow = 0;
            }

            result.addFirst(diff);
        }
        // 移除前导零
        while (!result.isEmpty() && result.getFirst() == 0) {
            result.removeFirst();
        }
        return result;
    }
    public static void main(String[] args) {

        LinkedList<Integer> l1 = new LinkedList<>();
        l1.add(9);
        l1.add(8);
        l1.add(1);

        LinkedList<Integer> l2 = new LinkedList<>();
        l2.add(5);
        l2.add(1);
        l2.add(2);
        LinkedList<Integer> result = subtract(l1, l2);
        for (Integer digit : result) {
            System.out.print(digit);
        }
    }
}
